<style scoped>
    .uploadbox{
        width:300px;
        height:120px;
        border:1px dashed #eee;
        text-align: center;
        line-height: 2;
        padding-top:30px;
    }
    .uploadbox .ad-image{
        width:300px;
        height:120px;
    }
</style>
<template>
    <div class="page-container is-form">
        <a-spin :spinning="spinning">
            <a-form :layout="formLayout" :form="form">
                <a-form-item label="广告标题" v-bind="formItemLayout">
                    <a-input placeholder='请输入广告标题' v-decorator="['title',{rules: [{ required: true, message: '广告标题不能为空!' }]}]" style="width: 400px;"/>
                </a-form-item>
                <a-form-item label='广告图' v-bind="formItemLayout" help="建议图片 JPG、PNG、GIF格式，小于500k">
                    <a-upload @preview="handlePreview" :show-upload-list="false"
                              :action="uploadAction"  @change="handleChange">
                        <div class="uploadbox">
                            <img :src="model.imageUrl" v-if="model.imageUrl" class="ad-image" />
                            <div class="ant-upload-text" v-else><a-icon type="plus" /><br/>上传</div>
                        </div>
                    </a-upload>
                    <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
                        <img alt="example" style="width: 100%" :src="previewImage" />
                    </a-modal>
                    <a-input type="hidden" v-decorator="['imageUrl',{rules: [{ required: true, message: '请上传图片' }]}]" />
                </a-form-item>
                <a-form-item label="广告链接" v-bind="formItemLayout">
                    <a-input placeholder='请输入广告链接' v-decorator="['linkUrl',{rules: [{ required: true, message: '广告链接不能为空!' }]}]" style="width: 400px;"/>
                    <div class="default_tips">* 链接商品: /pages/goods/detail?id=XXX, XXX 为商品编码</div>
                    <div class="default_tips">* 链接分类: /pages/goods/category?id=XXX, XXX 为分类编码</div>
                    <div class="default_tips">* 链接活动: /pages/activity/index?id=XXX, XXX 为活动编码</div>
                    <div class="default_tips">* 自定义外链: 需在微信小程序平台配合设置, 否则无法访问</div>
                </a-form-item>
                <a-form-item label="广告位置" v-bind="formItemLayout">
                    <a-select v-decorator="['location',{rules:[{required:true,message:'请选择广告位置'}]}]" style="width:400px;">
                        <a-select-option v-for="item in locationList" :key="item.id" :value="item.code">{{item.name}}</a-select-option>
                    </a-select>
                </a-form-item>
                <a-form-item label="有效期至" v-bind="formItemLayout">
                    <a-date-picker v-decorator="['endDate']" style="width: 400px;"
                        format="YYYY-MM-DD HH:mm" placeholder="请选择有效期"
                        :disabledDate="disabledDate"
                        :showTime="{ defaultValue: moment('00:00', 'HH:mm') }"
                    />
                </a-form-item>
                <a-form-item :wrapperCol="{span:8,offset: 5}">
                    <a-button type='primary'  :loading="bntLoading" @click="onSubmit">保 存</a-button>
                </a-form-item>
            </a-form>
        </a-spin>
    </div>
</template>
<script>
    import {save,findDetail} from "../../api/advertising";
    import {findListByType} from "../../api/pubData";
    import moment from 'moment'
    export default {
        components: {},
        beforeCreate(){
            this.form = this.$form.createForm(this);
        },
        data() {
            return{
                formLayout:'horizontal',
                spinning:false,
                params:{
                    dataType:104,
                    id:0
                },
                uploadAction:this.UPLOAD_URL,
                bntLoading:false,
                previewVisible: false,
                previewImage: '',
                locationList:[],
                model:{}
            }
        },
        computed: {
            formItemLayout () {
                const { formLayout } = this
                return formLayout === 'horizontal' ? {
                    labelCol: { span:5},
                    wrapperCol: { span:16 },
                } : {}
            },
        },
        methods:{
            moment,
            disabledDate(current) {
                // Can not select days before today and today
                return current && current < moment().startOf('day');
            },
            handleCancel() {
                this.previewVisible = false
            },
            handlePreview(file) {
                this.previewImage = file.url || file.thumbUrl
                this.previewVisible = true
            },
            beforeUpload(file, fileList){
                const isJPG = file.type === 'image/jpeg';
                const isPNG = file.type === 'image/png';
                const isGif = file.type === 'image/gif';
                if (!isJPG && !isPNG && !isGif) {
                    this.$message.error('图片格式错误,请检查后重新上传!');
                    return false;
                }
                const isLt500KB = file.size / 1024 / 500
                if (!isLt500KB) {
                    this.$message.error('图片大小不合适,请上传小于500KB的图片!');
                    return false;
                }
                return true;
            },
            handleChange({file, fileList}) {
                if(file.status == 'error') {
                    return false;
                }
                if(file.status == 'done') {
                    if (file.response) {
                        this.model.imageUrl = file.response.data
                        this.form.setFieldsValue({'imageUrl': file.response.data});
                    }
                }
            },
            onSubmit(){
                this.bntLoading = true;
                this.form.validateFields(
                    (err,values) => {
                        if (!err) {
                            this.onSave(values);
                        }else{
                            this.bntLoading = false;
                        }
                    },
                )
            },
            async onSave(data){
                this.spinning = true;
                let form = {...this.model,...data}
                let resp = await save(form);
                this.spinning = false;
                let _this = this;
                if(this.qUtil.validResp(resp)){
                    this.$success({title:'保存成功!',okText:'确定',
                        onOk(){_this.$router.push({name:'AdList'});}
                    });
                }else{
                    this.$message.error(resp.msg||'保存失败')
                    this.bntLoading = false;
                }
            },
            async loadBaseData(){
                let resp = await findListByType(this.params.dataType)
                console.log("=====>",resp)
                if(this.qUtil.validResp(resp)){
                    this.locationList = resp.data.dataList || []
                }
            },
            async onLoad(){
                if(this.params.id == 0) return false;
                this.spinning = true;
                let resp = await findDetail(this.params.id);
                if(this.qUtil.validResp(resp)){
                    this.model = resp.data.model;
                    const {title,imageUrl,linkUrl,location} = resp.data.model;
                    let endDate = resp.data.model
                    if(endDate != null && endDate != ''){
                        endDate = moment(endDate)
                    }
                    this.form.setFieldsValue({title,imageUrl,linkUrl,endDate,location});
                }
                this.spinning = false;
            }
        },
        mounted(){
            this.params.id = this.$route.query.id;
            this.loadBaseData();
            this.onLoad();
        },
    }
</script>